<?php
require_once(dirname(__FILE__) . '/inc/config.inc.php');
IsModelPriv('goodsorder');
//不限制响应时间
@set_time_limit(0);

//获取上传文件信息
$tempfile      = $_FILES['file'];
$tempfile_name = $tempfile['name'];
$tempfile_size = $tempfile['size'];
$tempfile_ext  = strtolower(substr(strrchr($tempfile_name, '.'), 1));
$tempfile_tn = isset($_FILES['file']['tmp_name']) ? $_FILES['file']['tmp_name'] : '';

//强制限定的某些文件类型禁止上传
if(in_array($tempfile_ext, explode('|', 'php|pl|cgi|asp|aspx|jsp|php3|shtm|shtml')))
{
	echo '您上传的文件类型为：['.$tempfile_ext.']，该类文件不允许通过后台上传！' . __LINE__;
}


//检查文件类型,上传文件目录
if(in_array($tempfile_ext, explode('|', strtolower($cfg_upload_img_type))))
{
	$upload_url = 'image';
	$upload_dir = $cfg_image_dir;
}
else if(in_array($tempfile_ext, explode('|', strtolower($cfg_upload_soft_type))))
{
	$upload_url = 'soft';
	$upload_dir = $cfg_soft_dir;
}
else if(in_array($tempfile_ext, explode('|', strtolower($cfg_upload_media_type))))
{
	$upload_url = 'media';
	$upload_dir = $cfg_media_dir;
}


$save_type = $upload_url;


//检查文件大小
if($tempfile_size > $cfg_max_file_size)
{
	$array['code'] = 1;
	$array['msg'] = '您上传的文件超过系统设定最大文件上传限制！';
	echo json_encode($array);

}


//创建文件夹
if(!file_exists($upload_dir))
{
	mkdir($upload_dir);
}


//检查目录可写权限
if(@!is_writable($upload_dir))
{
	$array['code'] = 1;
	$array['msg'] = '上传目录没有可写权限！';
	echo json_encode($array);
}


$ymd = date('Ymd');
$upload_url .= '/'.$ymd;
$upload_dir .= '/'.$ymd;

if(!file_exists($upload_dir))
{
	mkdir($upload_dir);

	$fp = fopen($upload_dir.'/index.htm', 'w');
	fclose($fp);
}


//上传文件名称
$filename = time()."_".rand(100000,999999).'.'.$tempfile_ext;


//上传文件路径
$save_url = 'uploads/'.$upload_url.'/'.$filename;
$save_dir = $upload_dir.'/'.$filename;


if(file_exists($save_dir))
{
	$array['code'] = 1;
	$array['msg'] = '同名文件已经存在了！';
	echo json_encode($array);
}

//移动临时文件到指定目录
if(@move_uploaded_file($tempfile_tn, $save_dir))
{
	//添加数据库记录
	if (isset($_GET['id'])) {
		$id = $_GET['id'];
		$dosql->ExecNoneQuery("INSERT INTO `#@__uploads` (name, path, size, type, posttime, gongdanid) VALUES ('$filename', '$save_url', '$tempfile_size', '$save_type', '".time()."', $id)");
	} else {
		$dosql->ExecNoneQuery("INSERT INTO `#@__uploads` (name, path, size, type, posttime) VALUES ('$filename', '$save_url', '$tempfile_size', '$save_type', '".time()."')");
	}


	//上传成功，返回数组
	$array['code'] = 0;
	$array['msg'] = '咦？好像上传成功了呢。';
	$array['data']['src'] = "/" . $save_url;
	$array['image'] = $save_url;
	echo json_encode($array);
}
else
{
	$array['code'] = 1;
	$array['msg'] = '发生未知错误，上传失败！';
	echo json_encode($array);
}